package edu.mapi.ir.viewer;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.util.Vector;
import java.util.prefs.Preferences;

import javax.swing.AbstractAction;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.UIManager;

import edu.mapi.ir.gui.GuiUtils;
import edu.mapi.ir.viewer.comm.ViewerComms;

/**
 * @author ZP
 */
public class MazeViewer extends JFrame {

	private Maze maze = null;
	private Vector<GridPosition> grid = null;	
	private Preferences prefs = Preferences.systemNodeForPackage(MazeViewer.class);
	private String host = prefs.get("host", "127.0.0.1");
	private MazePanel mazePanel = new MazePanel();	
	
	public MazeViewer() {
		createMenus();		
		setTitle("MazeWalker");		
		setLayout(new BorderLayout(2,2));
		add(mazePanel, BorderLayout.CENTER);
	}
	
	private void createMenus() {
		JMenuBar menubar = new JMenuBar();
		
		JMenu file = new JMenu("File");
		
		AbstractAction connect = new AbstractAction("Connect...", GuiUtils.getIcon("imgs/start.png")) {
			public void actionPerformed(ActionEvent e) {
				String input = JOptionPane.showInputDialog(null, "Please provide the server hostname", "127.0.0.1");				
				if (input != null) {
					host = input;
					prefs.put("hostname", input);
					try {
						ViewerComms comms = new ViewerComms();
						comms.connect(host, 6000);
						grid = GridPosition.readString(comms.getGridXML());
						maze = Maze.readString(comms.getLabXML());
						maze.setGrid(grid);
						mazePanel.setMaze(maze);
						BeaconVisibility bv = new BeaconVisibility(maze, maze.getBeacon());
						mazePanel.addLayer(bv);
					}
					catch (Exception ex) {
						GuiUtils.errorMessage(MazeViewer.this, "Error connecting to server", ex.getMessage());
					}
				}
			}
		};		
		file.add(connect);

		file.addSeparator();
		
		file.add(new AbstractAction("Exit", GuiUtils.getIcon("imgs/exit.png")) {
			public void actionPerformed(ActionEvent e) {
				System.exit(0);
			}
		});		
		
		menubar.add(file);
		setJMenuBar(menubar);
	}
	
	public static void main(String[] args) {
		try
		{
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());			
		}
		catch(Exception e){
		}
		MazeViewer app = new MazeViewer();
		app.setIconImage(GuiUtils.getImage("imgs/r2d2.png"));
		app.setSize(800, 600);
		GuiUtils.centerOnScreen(app);
		app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		app.setVisible(true);
	}

}
